package com.dhcc.DRGsHosp.web.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openkoala.koala.commons.InvokeResult;
import org.openkoala.security.shiro.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.dhcc.DRGsHosp.facade.ICDFacade;
import com.dhcc.DRGsHosp.facade.dto.ParamMap;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * @title		:ICDController.java
 * @description	:
 * @author		:lileizheng
 * @date		:2015年8月12日
 * @version     :1.0
 * @copyright   :DHCC 2013-2014 
 */
@Controller
@RequestMapping("/matchIcd")
public class MatchIcdController {

	@Autowired
	private ICDFacade icdFacade;
	
	private static List<String> operpath = new ArrayList<String>();// ICD手术对照存放路径
	private static List<String> diagpath = new ArrayList<String>();// ICD手术对照存放路径
	/**
	 * 
	 *  matchICD.  
	 *  @Description：ICD自动对照
	 *  @Author LiuHongjun
	 *  @param icdVersion
	 *  @param icdType
	 *  @return 
	 *  @Date:2017年8月15日上午9:12:35
	 */
	@ResponseBody
	@RequestMapping(value = "matchICD")
	public InvokeResult matchICD(String icdVersion, String icdType){
		String userCode = CurrentUser.getUserAccount();
		return icdFacade.matchICD(icdVersion, userCode, icdType);
	}
	
	@ResponseBody
	@RequestMapping(value = "getICDMatchResult")
	public InvokeResult getICDMatchResult(String icdVersion, String icdType, String depCode){
		return icdFacade.getICDMatchResult(icdVersion, icdType, depCode);
	}
	
	@ResponseBody
	@RequestMapping(value = "getICDMatching")
	public InvokeResult getICDMatching(String param){
		ObjectMapper objectMapper = new ObjectMapper();
		Map<String, Object> json;
		try {
			json = objectMapper.readValue(param, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
			json = new HashMap<String, Object>();
		} 
		return icdFacade.getICDMatching(json);
	}
	
	@ResponseBody
	@RequestMapping(value = "getBJICD")
	public Object getBJICD(String icdType, String icdVersion, String icdValue, String icdValue1){
		return icdFacade.getBJICD(icdType, icdVersion, icdValue, icdValue1);
	}
	
	@ResponseBody
	@RequestMapping(value = "updateICDMatching")
	public InvokeResult updateICDMatching(String param){
		ObjectMapper objectMapper = new ObjectMapper();
		Map<String, Object> json = new HashMap<>();
		try {
			json = objectMapper.readValue(param, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		json.put("userCode", CurrentUser.getUserAccount());
		return icdFacade.updateICDMatching(json);
	}
	
	@ResponseBody
	@RequestMapping(value = "getEditLog")
	public InvokeResult getEditLog(String hICDCode, String icdVersion){
		return icdFacade.getEditLog(hICDCode, icdVersion);
	}
	
	@ResponseBody
	@RequestMapping(value = "icdImport")
	public InvokeResult icdImport(String icdType, String param){
		ObjectMapper objectMapper = new ObjectMapper();
		Map<String, Object> json = new HashMap<>();
		try {
			json = objectMapper.readValue(param, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		json.put("userCode", CurrentUser.getUserAccount());
		return icdFacade.icdImport(icdType, json);
	}
	/**
	 *  @Discription：统计对照情况
	 *  @Author： liuhongjun
	 *  @param icdType
	 *  @param isOnlyMatch
	 *  @return
	 *  @Date:2018年11月13日上午8:33:14
	 */
	@ResponseBody
	@RequestMapping(value = "/getICDMatchResultTable")
	public InvokeResult getICDMatchResultTable(String icdType, String isOnlyMatch){
		return icdFacade.getICDMatchResultTable(icdType, isOnlyMatch);
	}
	/**
	 *  @Discription：ICD对照平台用
	 *  @Author： qiaoyilong
	 *  @Date:2018年11月16日下午1:33:14
	 */
	@ResponseBody
	@RequestMapping(value = "/getICDMatchResultTablePlatform")
	public InvokeResult getICDMatchResultTablePlatform(String icdType,String icdVersion, String isOnlyMatch){
		return icdFacade.getICDMatchResultTablePlatform(icdType,icdVersion, isOnlyMatch);
	}	
	/**
	 * 
	 * @methodname :fileUploadICD
	 * @Description : ICD对照文件上传
	 * @author:yujiaolong
	 * @return InvokeResult
	 * @date :2017年5月12日
	 */

	@ResponseBody
	@RequestMapping("/fileUploadICD")
	public InvokeResult fileUploadICDOper(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException {
		//return icdFacade.getICDMatchResultTable(icdType, isOnlyMatch);
		operpath = new ArrayList<String>();
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得request中的所有文件名
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 记录上传过程起始时的时间，用来计算上传时间
				int pre = (int) System.currentTimeMillis();
				// 取得上传文件
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					// 取得当前上传文件的文件名称
					String myFileName = file.getOriginalFilename();
					// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
					if (myFileName.trim() != "") {
						System.out.println(myFileName);
						// 重命名上传后的文件名
						String fileName =UUID.randomUUID()+"-"+file.getOriginalFilename();
						// 定义上传路径
						String path = request.getSession().getServletContext().getRealPath("/") + "upload";						
						File localFile = new File(path);
						if (!localFile.exists()) {
							localFile.mkdirs();
						}
						localFile = new File(path + File.separatorChar + fileName);
						try {
							file.transferTo(localFile);
							operpath.add(path + File.separatorChar + fileName);
						} catch (Exception e) {
							e.printStackTrace();
						} // 文件上传至服务器
					}
				}
				// 记录上传该文件后的时间
				int finaltime = (int) System.currentTimeMillis();
			}
		}
		  return InvokeResult.success();
	}
	
	/**
	 * 
	 * @methodname :analysisICDOper
	 * @Description : ICD手术对照文件解析
	 * @author:yujiaolong
	 * @return InvokeResult
	 * @date :2017年5月12日
	 */
	@ResponseBody
	@RequestMapping(value = "/analysisICDOper")
	//String icdVersion, String icdType,
	public InvokeResult analysisICDOper(String icdType,String icdVersion,HttpServletRequest request, HttpServletResponse response) {		  
		 boolean flag = true;
		 String userCode=CurrentUser.getUserAccount();
	     for (String filePath : operpath) {
	    	 if(!icdFacade.analysisICD(icdType,icdVersion,userCode,filePath).isSuccess()){
	    		 flag = false;
	    	 }				
		}
	    operpath = new ArrayList<String>();
	    if(flag == true){
	    	return InvokeResult.success();
	    }
	    else{
	    	return InvokeResult.failure("");
	    }
	}
	
	
	
	
	/**
	 * @methodname :fileUploadICDDiag
	 * @Description : ICD诊断对照文件上传
	 * @author:yujiaolong
	 * @return InvokeResult
	 * @date :2017年5月13日
	 */
	@ResponseBody
	@RequestMapping("/fileUploadICDDiag")
	public InvokeResult fileUploadICDDiag(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException {
		diagpath = new ArrayList<String>();
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得request中的所有文件名
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 记录上传过程起始时的时间，用来计算上传时间
				int pre = (int) System.currentTimeMillis();
				// 取得上传文件
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					// 取得当前上传文件的文件名称
					String myFileName = file.getOriginalFilename();
					// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
					if (myFileName.trim() != "") {
						System.out.println(myFileName);
						// 重命名上传后的文件名
						String fileName =UUID.randomUUID()+"-"+myFileName;
						// 定义上传路径
						String path = request.getSession().getServletContext().getRealPath("/") + "upload";						
						File localFile = new File(path);
						if (!localFile.exists()) {
							localFile.mkdirs();
						}
						localFile = new File(path + File.separatorChar + fileName);
						try {
							file.transferTo(localFile);
							diagpath.add(path + File.separatorChar + fileName);
						} catch (Exception e) {
							e.printStackTrace();
						} // 文件上传至服务器
					}
				}
				// 记录上传该文件后的时间
				int finaltime = (int) System.currentTimeMillis();
			}
		}
		return InvokeResult.success();
	}
	
	/**
	 * 
	 * @methodname :analysisICDOper
	 * @Description : ICD诊断对照文件解析
	 * @author:yujiaolong
	 * @return InvokeResult
	 * @date :2017年5月13日
	 */
	@ResponseBody
	@RequestMapping(value = "/analysisICDDiag")
	//String icdVersion, String icdType,
	public InvokeResult analysisICDDiag(String icdType,String icdVersion,HttpServletRequest request, HttpServletResponse response) {		  
		 boolean flag = true;
		 String userCode=CurrentUser.getUserAccount();
	     for (String filePath : diagpath) {
	    	 if(!icdFacade.analysisICD(icdType,icdVersion,userCode,filePath).isSuccess()){
	    		 flag = false;
	    	 }				
		}
	    diagpath = new ArrayList<String>();
	    if(flag == true){
	    	return InvokeResult.success();
	    }
	    else{
	    	return InvokeResult.failure("");
	    }
	}
	
	
	/**
	 * 
	 * @methodname :updateOneICD
	 * @Description : 一条ICD的增加或者修改
	 * @author:yujiaolong
	 * @return InvokeResult
	 * @date :2017年5月23日
	 */
	@ResponseBody
	@RequestMapping(value = "/updateOneICD")
	//String icdVersion, String icdType,
	public InvokeResult updateOneICD(HttpServletRequest request, HttpServletResponse response) {		  
		Map<String,Object> dto=new ParamMap().newMap(request);
		dto.put("userCode", CurrentUser.getUserAccount());
		return icdFacade.updateOneICD(dto);
	}

	/**
	 * 
	 * @methodname :updateOneICD
	 * @Description : 一条ICD的增加或者修改（ICD对照平台用）
	 * @author:qiaoyilong
	 * @date :2018年11月16日
	 */
	@ResponseBody
	@RequestMapping(value = "/updateOneICDPlatform")
	public InvokeResult updateOneICDPlatform(HttpServletRequest request, HttpServletResponse response) {		  
		Map<String,Object> dto=new ParamMap().newMap(request);
		dto.put("userCode", CurrentUser.getUserAccount());
		return icdFacade.updateOneICDPlatform(dto);
	}
	
	/**
	 *  findDescByCode.  
	 *  @Description：根据编码获取描述
	 *  @Author LiuHongjun
	 *  @param code
	 *  @param type
	 *  @return 
	 *  @Date:2017年8月25日下午3:11:23
	 */
	@ResponseBody
	@RequestMapping(value = "/findDescByCode")
	public InvokeResult findDescByCode(String code,String type) {		  
		return icdFacade.findDescByCode( code, type);
	}
	/**
	 * 
	 *  findBJDescByCode.  
	 *  @Description：根据BJ编码获取描述
	 *  @Author LiuHongjun
	 *  @param code
	 *  @param type
	 *  @return 
	 *  @Date:2017年8月25日下午3:28:55
	 */
	@ResponseBody
	@RequestMapping(value = "/findBJDescByCode")
	public InvokeResult findBJDescByCode(String code,String type, String icdVersion) {		  
		return icdFacade.findBJDescByCode(code, type, icdVersion);
	}
	/**
	 * 
	 *  getICDMatchResultTable.  
	 *  @Description：获取进度
	 *  @Author LiuHongjun
	 *  @param icdType
	 *  @param isOnlyMatch
	 *  @return 
	 *  @Date:2017年8月29日上午9:29:14
	 */
	@ResponseBody
	@RequestMapping(value = "/findUploadProgress")
	public InvokeResult findUploadProgress(){
		return icdFacade.findUploadProgress();
	}
	/**
	 * 
	 *  batchSummitIcd.  
	 *  @Description：批量处理提交信息
	 *  @Author LiuHongjun
	 *  @return 
	 *  @Date:2017年8月30日上午11:27:01
	 */
	@ResponseBody
	@RequestMapping(value = "/batchSummitIcd")
	public InvokeResult batchSummitIcd(String icdType, String matchType, String icdVersion){
		return icdFacade.batchSummitIcd(icdType, matchType, icdVersion);
	}
	/**
	 * 
	 *  findBjIcdCode.  
	 *  @Description：获取北京icd
	 *  @Author LiuHongjun
	 *  @param icdVersion bjICD版本
	 *  @param icdType icd类型：o手术，d诊断
	 *  @return 
	 *  @Date:2017年9月4日下午8:58:14
	 */
	@ResponseBody
	@RequestMapping(value = "/findBjIcdCode")
	public InvokeResult findBjIcdCode(String icdVersion,String icdType){
		return icdFacade.findBjIcdCode(icdVersion,icdType);
	}
	/**
	 * 
	 *  updateMrIsOper.  
	 *  @Description：更新手术表中的手术/操作字段
	 *  @Author ZouYiyu
	 *  @param dateFrom
	 *  @param dateTo
	 *  @return 
	 *  @Date:2017年10月26日上午9:41:16
	 */
	@ResponseBody
	@RequestMapping(value="/updateMrIsOper")
	public InvokeResult updateMrIsOper(String dateFrom,String dateTo){
		icdFacade.updateMrIsOper(dateFrom, dateTo);
		return InvokeResult.success();
	}
	/**
	 * 
	 *  operDicType.  
	 *  @Description：查询数据库中icd字典版本
	 *  @Author ZouYiyu
	 *  @param icdType
	 *  @return 
	 *  @Date:2017年11月16日下午5:19:52
	 */
	@ResponseBody
	@RequestMapping(value="/operDicType")
	public List<Map<String, Object>> operDicType(String icdType){
		return icdFacade.operDicType(icdType);
	}
	
	/**
	 * 
	 * @methodname    :getNoCompareCase
	 * @description   : 根据未对照上诊断编码查病例明细
	 * @param         :
	 * @author        :sulina
	 * @return        :
	 * @date          :2018年11月15日
	 */
	@ResponseBody
	@RequestMapping("/getNoCompareCase")
	public InvokeResult notInDiagCaseData(String icdCode,String icdType,String icdDesc){
		return InvokeResult.success(icdFacade.getNoCompareCase(icdCode,icdDesc,icdType));
	}
	
	/**
	 * 
	 * @methodname :analysisICDPlatform
	 * @Description : ICD诊断对照文件解析(ICD对照平台页面用)
	 * @author:qiaoyilong
	 * @date :2018年11月17日
	 */
	@ResponseBody
	@RequestMapping(value = "/analysisICDPlatform")
	public InvokeResult analysisICDPlatform(String icdType,String icdVersion,HttpServletRequest request, HttpServletResponse response) {		  
		 boolean flag = true;
		 String userCode=CurrentUser.getUserAccount();
		/* if("D".equals(icdType)){
		     for (String filePath : diagpath) {
		    	 if(!icdFacade.analysisICDPlatform(icdType,icdVersion,userCode,filePath).isSuccess()){
		    		 flag = false;
		    	 }				
			}
		    diagpath = new ArrayList<String>();			 
		 }else{
		     for (String filePath : operpath) {
		    	 if(!icdFacade.analysisICDPlatform(icdType,icdVersion,userCode,filePath).isSuccess()){
		    		 flag = false;
		    	 }				
			}
		    operpath = new ArrayList<String>();
		 }*/
		 for (String filePath : operpath) {
	    	 if(!icdFacade.analysisICDPlatform(icdType,icdVersion,userCode,filePath).isSuccess()){
	    		 flag = false;
	    	 }				
		}
	    operpath = new ArrayList<String>();
	    if(flag == true){
	    	return InvokeResult.success();
	    }
	    else{
	    	return InvokeResult.failure("");
	    }
	}
	
}

